import {Inject, Provide} from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import {makeHttpRequest} from "@midwayjs/core";
import {Repository} from "typeorm";
import {BaseSysUserEntity} from "../../base/entity/sys/user";
import {CacheManager} from "@midwayjs/cache";
import {InjectEntityModel} from "@midwayjs/typeorm";
import * as md5 from 'md5';
import {DemoShipsEntity} from "../entity/ships";

/**
 * 缓存
 */
@Provide()
export class WxApiService extends BaseService {

  @Inject()
  ctx;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @InjectEntityModel(DemoShipsEntity)
  demoShipsEntity: Repository<DemoShipsEntity>;

  @Inject()
  cacheManager: CacheManager;

  async getAccessToken() {
    // let url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'+'&appid=wx3d5b856d68f77bae'
    //   +'&secret=e7db02dc0bdebca09058ed6f550235bd';
    // const accessTokenRes = await makeHttpRequest(url, {
    //   // 必须指定 method
    //   method: 'GET',
    //   // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
    //   contentType: 'json',
    //   data: {},
    //   // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
    //   dataType: 'json',
    // });
    // console.log(accessTokenRes.data,'==================')
    // console.log(accessTokenRes.data.data.access_token,'accessTokenResaccessTokenRes')
    let accessToken = await this.cacheManager.get('accessToken')
    return accessToken
  }

  async getOpenid(body) {
    let url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+'wxc9554905b112cd47'+'&secret='+'81ce888c9033e1e6da494b72abd88a38'
      +'&js_code='+body.code+'&grant_type=authorization_code';
    const accessTokenRes = await makeHttpRequest(url, {
      // 必须指定 method
      method: 'GET',
      // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
      contentType: 'json',
      data: {},
      // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
      dataType: 'json',
    });
    return accessTokenRes.data
  }

  async login(body){
    let user = await this.baseSysUserEntity.findOneBy({
      username: body.username,
      password: md5(body.password)
    })
    console.log(user)
    if (user){
      return user
    }
    return "fail"
  }

  async getShipsList(body){
    let data = await this.demoShipsEntity.findBy({userId: body.userId})
    console.log(data)
    return data
  }
}
